package fr.greta.centreFormation.controller;

import java.io.IOException;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import fr.greta.centreFormation.bean.Candidat;

public class Upload extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final String UPLOAD_DIRECTORY = "upload";
	private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
	private static final int REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = (String) request.getSession(true).getAttribute("login");
		
		
		// vérifie si la requete contient un fichier
		if (!ServletFileUpload.isMultipartContent(request)) {
			// sinon, s'arrete ici
			return;
		}

		// configuration de certains parametres
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(THRESHOLD_SIZE);
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(MAX_FILE_SIZE);
		upload.setSizeMax(REQUEST_SIZE);

		// construit le chemin du dossier pour stocker la fichier reçu
		String uploadPath = getServletContext().getRealPath("")
				+ File.separator + UPLOAD_DIRECTORY;
		// creer le répertoire si celui-ci n'existe pas
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}

		try {
			// parse la demande pour stocker les donnees
			List<FileItem> formItems = upload.parseRequest(request);
			String message = null;
			// iterates over form's fields
			for (FileItem item : formItems) {
				// processes only fields that are not form fields
				if (!item.isFormField()) {
					//String fileName = new File(item.getName()).getName();
					String fileName = login + ".jpg";
					String filePath = uploadPath + File.separator + fileName;
					File storeFile = new File(filePath);

					// sauve le fichier sur le disque
					item.write(storeFile);
					request.setAttribute("message", "Photo enregistrée sous "
							+ filePath);
				}
			}
		} catch (Exception ex) {
			request.setAttribute("message", "Erreur: " + ex.getMessage());
		}
		getServletContext().getRequestDispatcher("/espaceEtudiant.jsp")
				.forward(request, response);
	}
}
